<?php
namespace app\admin\controller;
use think\Controller;
class Operators extends Common
{
    public function templateList()
    {
        $keyword = input('keyword');
        $adminId = input('admin_id');
        $tagId = input('tag_id');
        $groupId = session('group_id','','admin');
        $tagAllList = db('template_tag_list')->order('id DESC')->select();
        foreach($tagAllList as $k=>$v)
        {
            $tagAllList[$k]['count'] = db('template_tag')->alias('t')->join('template_list l','t.template_id = l.id')->where('l.is_del',0)->where('t.tag_id',$v['id']);
            if($adminId)
                $tagAllList[$k]['count'] = $tagAllList[$k]['count']->where('l.admin_id',$adminId);
            $tagAllList[$k]['count'] =  $tagAllList[$k]['count']->count();
        }
        $staffList = db('admin')->where('group_id',7)->select();
        $this->assign([
            'keyword'=>$keyword,
            'admin_id'=>$adminId,
            'tag_id'=>$tagId,
            'group_id'=>$groupId,
            'tag_list'=>$tagAllList,
            'staffList'=>$staffList,
        ]);
        return view();
        
    }
    
    public function templateListData()
    {
        $keyword = input('keyword');
        $adminId = input('admin_id');
        $tagId = input('tag_id');
        $page = input('page')?input('page'):1;
        $config['query'] = ['keyword'=>$keyword,'admin_id'=>$admin_id];
        $groupId = session('group_id','','admin');
        $list = db('template_list')->alias('l')->field('l.*')->where('l.is_del',0);
        $count = db('template_list')->alias('l')->field('l.*')->where('l.is_del',0);
        // if($groupId == 7)
        // {
        //     $list = $list->where('l.admin_id',$adminId);
        //     $count = $count->where('l.admin_id',$adminId);
        // }
        if($keyword)
        {
            $list = $list->where("l.name LIKE '%{$keyword}%' OR l.id = {$keyword}");
            $count = $count->where("l.name LIKE '%{$keyword}%' OR l.id = {$keyword}");
        }
        if($adminId)
        {
            $list = $list->where("l.admin_id",$adminId);
            $count = $count->where("l.admin_id",$adminId);
        }
        if($tagId)
        {
            $list = $list->join('template_tag t','l.id = t.template_id')->where("t.tag_id",$tagId);
            $count = $count->join('template_tag t','l.id = t.template_id')->where("t.tag_id",$tagId);
        }
        $list = $list->order('l.id desc')->page($page,12)->select();
        $count = $count->count();
        foreach($list as $k=>$v)
        {
            $list[$k]['admin_name'] = db('admin')->where('id',$v['admin_id'])->value('name');
            $list[$k]['tagsHtml'] = '';
            $tagList = db('template_tag')->alias('t')->join('template_tag_list tl','t.tag_id = tl.id')->where('t.template_id',$v['id'])->select();
            if($tagList)
            {
                foreach ($tagList as $kk=>$vv)
                {
                    $list[$k]['tagsHtml'] .= '<span class="tagname">'.$vv['name'].'</span>';
                }
            }
            
        }
        return json(['list'=>$list,'count'=>$count]);
    }
    
    public function templateInfo()
    {
        if(input('id'))
        {
            $id = input('id');
            $adminId = session('uid','','admin');
            $info = db('template_list')->where('id',$id)->find();
            $tagList = db('template_tag')->alias('t')->join('template_tag_list tl','t.tag_id = tl.id')->where('t.template_id',$id)->select();
            $tagAllList = db('template_tag_list')->order('id DESC')->select();
            $this->assign([
                'info'=>$info,
                'tagList'=>$tagList,
                'tagAllList'=>$tagAllList,
            ]);
            if($info['admin_id'] == $adminId)
                return view('template_edit');
            else
                return view();
        }
    }
    
    public function templateEdit()
    {
        if(request()->isAjax())
        {
            $data = input('post.');
            $data['name'] = trim($data['name']);
            if(!$data['id'])
            {
                $data['admin_id'] = session('uid','','admin');
                $data['add_time'] = time();
                $id = db('template_list')->insertGetId($data);
                if($id)
                {
                    if($data['tags'])
                    {
                        foreach ($data['tags'] as $k=>$v)
                        {
                            db('template_tag')->insert(['template_id'=>$id,'tag_id'=>$v]);
                        }
                    }
                    return ['msg'=>'操作成功','icon'=>1];
                }
                else
                {
                    return ['msg'=>'操作失败','icon'=>2];
                }
            }
            else
            {
                $sqlStatus = db('template_list')->update($data);
                db('template_tag')->where('template_id',$data['id'])->delete();
                if($data['tags'])
                {
                    foreach ($data['tags'] as $k=>$v)
                    {
                        db('template_tag')->insert(['template_id'=>$data['id'],'tag_id'=>$v]);
                    }
                }
                return ['msg'=>'操作成功','icon'=>1];
            }
        }
        else
        {
            $tagAllList = db('template_tag_list')->order('id DESC')->select();
            $this->assign([
                'tagAllList'=>$tagAllList,
            ]);   
            return view();
        }
            
    }
    
    public function templateDel()
    {
        if(input('id'))
        {
            $sqlStatus = db('template_list')->where('id',input('id'))->setField('is_del', '1');
            if($sqlStatus)
            {
                return ['msg'=>'操作成功','icon'=>1];
            }
            else
            {
                return ['msg'=>'操作失败','icon'=>2];
            }
        }
    }
    
    public function templateMutiplyUpload()
    {
        $file = request()->file('block');
        if($file)
        {
            $total = input('total');
            $index = input('index');
            $info = $file->move( '../uploads/todaystar');
            if($info)
            {
                $result = '../uploads/todaystar/'.$info->getSaveName();
                session($index,$result,'task');
                if($index == $total)
                {
                    $list = session('','','task');
                    $fp = fopen('./uploads/todaystar/'.session('task_name'),"ab");
                    foreach($list as $value)
                    {  
                        if(!empty($value))
                        {  
                            $handle = fopen($value,"rb");  
                            fwrite($fp,fread($handle,filesize($value)));  
                            fclose($handle);  
                            unset($handle);  
                        }  
                    }  
                    fclose($fp);
                    $zipName = $_SERVER['DOCUMENT_ROOT'].iconv('UTF-8', 'GB2312', '/uploads/todaystar/'.session('task_name'));
                    $toDir = substr($zipName,0,-4);
                    
                    $zip = new \PclZip\PclZip();
                    $zip->PclZip(iconv('utf-8', 'gbk', $zipName));
                    $unzip = $zip->extract(PCLZIP_OPT_PATH, $toDir);
                    if($unzip == 0)
                    {
                        return ['code'=>-1,$zip->errorInfo(true)];
                    }
                    else
                    {
                        $teamList = getDirContent($toDir);
                        foreach ($teamList as $k=>$v)
                        {
                            $templateList = getDirContent($toDir.'/'.$v);
                            foreach ($templateList as $kk=>$vv)
                            {
                                if(explode('.',$vv)[1])
                                {
                                    $data['name'] = explode('.',$vv)[0];
                                    $data['pic_path'] = '/uploads/todaystar/'.substr(session('task_name'),0,-4).'/'.$v.'/'.$vv;
                                    $data['add_time'] = time();
                                    $data['admin_id'] = session('uid','','admin');
                                    db('template_list')->insert($data);
                                    unset($data);
                                }
                            }
                            if(explode('.',$v)[1])
                            {
                                $data['name'] = explode('.',$v)[0];
                                $data['pic_path'] = '/uploads/todaystar/'.substr(session('task_name'),0,-4).'/'.$v;
                                $data['add_time'] = time();
                                $data['admin_id'] = session('uid','','admin');
                                db('template_list')->insert($data);
                                unset($data);
                            }
                        }
                        return ['code'=>1,'task_name'=>session('task_name')];
                    }
                }
                return ['code'=>0,'data'=>$result];
            }
            else
            {
                return ['code'=>-1,'msg'=>$file->getError()];
            }
        }
        else
        {
            session(null,'task');
            session('task_name', rand(1,900).time().'.zip' );
            
            return view();
        }
    }
    
    
    
    public function addTag()
    {
        if(request()->isAjax())
        {
            $data = input('post.');
            $data['name'] = trim($data['tag_name']);
            $id = db('template_tag_list')->where('name',$data['name'])->value('id');
            if(!$id)
            {
                $data['admin_id'] = session('uid','','admin');
                $data['add_time'] = time();
                $id = db('template_tag_list')->insertGetId($data);
            }
            if($id)
            {
                return ['id'=>$id,'msg'=>'操作成功'];
            }
            else
            {
                return ['msg'=>'操作失败','icon'=>2];
            }
        } 
    }
    
    public function editTag()
    {
        if(request()->isAjax())
        {
            $data = input('post.');
            $data['name'] = trim($data['tag_name']);
            $id = db('template_tag_list')->where('id',$data['id'])->update(['name'=>$data['name']]);
            return ['msg'=>'操作成功','icon'=>1];
        } 
    }
    
    public function uploadTemplatePic()
    {
        $file = request()->file('file');
        $info = $file->move( './uploads/template_pic/');
        if($info)
        {
            return ['code'=>0,'pic_path'=>'/uploads/template_pic/'.$info->getSaveName()];
        }
        else{
            return ['code'=>-0,'msg'=>$info->getError()];
        }
        
    }
    

    
    public function topicLog()
    {
        $keyword = input('keyword');
        $admin_id = input('admin_id');
        $start_date = input('start_date');
        $end_date = input('end_date');
        $my = input('my');
        $config['query'] = ['my'=>$my,'keyword'=>$keyword,'admin_id'=>$admin_id,'start_date'=>$start_date,'end_date'=>$end_date];
        $adminId = session('uid','','admin');
        $groupId = session('group_id','','admin');

        $list = db('active_page_log')->where('is_del',0);
        if($groupId == 7)
        {
            $list = $list->where('admin_id',$adminId);
        }
        if($keyword)
        {
            $list = $list->where("activity_name LIKE '%{$keyword}%' OR staff_name LIKE '%{$keyword}%'");
        }
        if($start_date)
        {
            $list = $list->whereTime("complete_time",'>=',$start_date);
        }
        if($end_date)
        {
            $list = $list->whereTime("complete_time",'<=',$end_date.' 23:59:59');
        }
        if($admin_id)
        {
            $list = $list->where("admin_id",$admin_id);
        }
        // if($my == 1)
        // {
        //     if(in_array($groupId,[2,5]) )
        //         $list = $list->where('to_admin_id',$_SESSION['admin']['uid']);
        // } 
        if(in_array($groupId,[2,5]) ){
            $list = $list->where('to_admin_id',$_SESSION['admin']['uid']);
        }
        $list = $list->order('id desc')->paginate(10,false,$config);
//         echo "<pre>";
//         print_r($list);
//         die;

        $staffList = db('admin')->where('group_id',7)->where('status',1)->select();
        
        //单页&子页 统计
        $list_arr = $list->toArray();

        $single_count = 0;//单页
        $topic_count = 0;//子页

        foreach($list_arr['data'] as $key => $val){
            if($val['topic_count'] == 0){
                $single_count = $single_count + 1;
            }else{
                if($val['topic_count'] > 15){
                    $topic_count = $topic_count + 15;
                }else{
                    $topic_count = $topic_count + $val['topic_count'];
                }
            }
        }
        
        $this->assign([
            'list'=>$list,
            'count'=>$list->total(),
            'staffList'=>$staffList,
            'single_count'=>$single_count,
            'topic_count'=>$topic_count,
        ]);
        return view();
    }
    
    public function topicLogAdd()
    {
        if(request()->isAjax())
        {
            $data = input('post.')['data'];
            $data['admin_id'] = session('uid','','admin');
            $data['add_time'] = time();
            $data['complete_time'] = strtotime($data['complete_time']);
            $data['staff_name'] = db('admin')->where('id',$data['to_admin_id'])->value('name');
            $sqlStatus = db('active_page_log')->insert($data);
            
            if($sqlStatus  )
            {
                return ['msg'=>'操作成功','icon'=>1];
            }
            else
            {
                return ['msg'=>'操作失败','icon'=>2];
            }
        }
        $staffList = db('admin')->where('group_id','in','2,5')->where('status',1)->orderRaw('CONVERT(name USING gbk)')->select();
        $this->assign([
            'staffList'=>$staffList,
        ]);
        return view();
    }
    
    public function topicLogEdit()
    {
        if(input('id'))
        {
            if(request()->isAjax())
            {
                $data = input('post.')['data'];
                $data['id'] = input('id');
                $data['admin_id'] = session('uid','','admin');
                // $data['add_time'] = time();
                $data['complete_time'] = strtotime($data['complete_time']);
                $data['staff_name'] = db('admin')->where('id',$data['to_admin_id'])->value('name');
                $sqlStatus = db('active_page_log')->update($data);
                if($sqlStatus  )
                {
                    return ['msg'=>'操作成功','icon'=>1];
                }
                else
                {
                    return ['msg'=>'操作失败','icon'=>2];
                }
            }
            $info = db('active_page_log')->where('id',input('id'))->find();
            $staffList = db('admin')->where('group_id','in','2,5')->where('status',1)->order('name asc')->select();
        	$this->assign([
        		'info'=>$info,
        		'staffList'=>$staffList,
        	]);
            return view('topic_log_add');
        }
    }
    
    public function topicLogCheck()
    {
        if(input('id'))
        {
            if(request()->isAjax())
            {
                $data = input('post.')['data'];
                $sqlStatus = db('active_page_log')->where('id',input('id'))->update($data);
                if($sqlStatus  )
                {
                    return ['msg'=>'操作成功','icon'=>1];
                }
                else
                {
                    return ['msg'=>'操作失败','icon'=>2];
                }
            }
            $info = db('active_page_log')->where('id',input('id'));
            if(session('group_id','','admin')!=1)
                $info = $info->where('to_admin_id',session('uid','','admin'));
            $info = $info->find();
        	$this->assign([
        		'info'=>$info,
        	]);
            return view();
        }
    }
    
    public function topicLogView()
    {
        if(input('id'))
        {
            $info = db('active_page_log')->find(input('id'));

            $this->assign([
                'info'=>$info,
            ]);
            return view();
        }
    }
    
    public function topicLogDel()
    {
        if(input('id'))
        {
            $sqlStatus = db('active_page_log')->where('id',input('id'))->setField('is_del', '1');;
            if($sqlStatus)
            {
                return ['msg'=>'操作成功','icon'=>1];
            }
            else
            {
                return ['msg'=>'操作失败','icon'=>2];
            }
        }
    }
    
}